package com.woniuxy.rdbc.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.rdbc.dto.UserDto;
import com.woniuxy.rdbc.entity.SysDept;
import com.woniuxy.rdbc.entity.SysUser;
import com.woniuxy.rdbc.service.DeptService;
import com.woniuxy.rdbc.service.UserService;
import com.woniuxy.rdbc.util.Result;
import com.woniuxy.rdbc.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private DeptService deptService;
    @PostMapping("login")
    public Result login(@RequestBody UserDto userDto){
        SysUser sysUser = userService.SelectByTelAndPsw(userDto);
        return sysUser!=null?Result.ok():Result.error();
    }
    @PostMapping("querry")
        public Result querry(@RequestBody  UserDto userDto){
        PageHelper.startPage(userDto.getCurrentPage(), userDto.getPageSize(), "true");
        PageHelper.orderBy("id desc");
        List<UserVo> userVos = userService.selectByLike(userDto);
        List<SysDept> sysDepts = deptService.selectAll();

        PageInfo<UserVo> pageInfo = new PageInfo<>(userVos);

        return Result.ok().data("list",userVos).data("tool",pageInfo.getTotal()).data("dept",sysDepts);
    }
    @PostMapping("addUser")
    public Result add(@RequestBody SysUser sysUser){
        System.out.println(sysUser.toString());
        SysUser sysUser1 = userService.selectByTel(sysUser.getTel());
        if (sysUser1 != null) {
            return Result.error();
        }
        userService.insertSelective(sysUser);
        return Result.ok();
    }
    @DeleteMapping("{id}")
    public Result delUser(@PathVariable Long id){
        int i = userService.deleteByPrimaryKey(id);
        return i>0?Result.ok():Result.error();
    }
    @GetMapping("{id}")
    public Result editUser(@PathVariable Long id){
        SysUser sysUser = userService.selectByPrimaryKey(id);
        return Result.ok().data("user",sysUser);
    }

    @PutMapping("")
    public Result updateUser(@RequestBody SysUser sysUser){
        int i = userService.updateByPrimaryKeySelective(sysUser);
        return i>0?Result.ok():Result.error();
    }
}
